package rexsee.multimedia;

import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.JavascriptInterface;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;

public class RexseeAudio implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Audio";
	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return new RexseeAudio(childBrowser);
	}

	public static final String EVENT_ONAUDIOMERGED = "onAudioMerged";

	public final Context mContext;
	private final Browser mBrowser;
	private final ArrayList<String> filesToBeMerge = new ArrayList<String>();

	public RexseeAudio(Browser browser) {
		mBrowser = browser;
		mContext = browser.getContext();
		mBrowser.eventList.add(EVENT_ONAUDIOMERGED);
	}

	//JavaScript Interface

	/**
	  * 需求:将两个amr格式音频文件合并为1个
	  * 注意:amr格式的头文件为6个字节的长度
	  * @param partsPaths      各部分路径
	  * @param unitedFilePath  合并后路径
	  */
	public void clearMergeList() {
		filesToBeMerge.clear();
	}
	public void addToMergeList(String file) {
		filesToBeMerge.add(file);
	}
	public int getCountOfMergeList() {
		return filesToBeMerge.size();
	}
	public boolean existsInMergeList(String file) {
		return filesToBeMerge.contains(file);
	}
	public String getFromMergeList(int position) {
		return (position > filesToBeMerge.size() - 1 || position < 0) ? "" : filesToBeMerge.get(position);
	}
	public void remove(String file) {
		filesToBeMerge.remove(file);
	}
	public void merge(final String unitedFilePath) {
		new Thread() {
			@Override
			public void run() {
				try {
					File unitedFile = new File(Uri.parse(unitedFilePath).getPath());
					FileOutputStream fos = new FileOutputStream(unitedFile);
					RandomAccessFile ra = null;
					for (int i = 0; i < filesToBeMerge.size(); i++) {
						ra = new RandomAccessFile(Uri.parse(filesToBeMerge.get(i)).getPath(), "r");
						if (i != 0) {
							ra.seek(6);
						}
						byte[] buffer = new byte[1024 * 8];
						int len = 0;
						while ((len = ra.read(buffer)) != -1) {
							fos.write(buffer, 0, len);
						}
					}
					ra.close();
					fos.close();
					((Activity) mContext).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							mBrowser.eventList.run(EVENT_ONAUDIOMERGED, new String[]{unitedFilePath});
						}
					});
				} catch (Exception e) {
				}
			}
		}.start();
	}

}
